package cn.cj.erp.modules.login.controller;

import cn.cj.erp.common.enums.StatusEnum;
import cn.cj.erp.common.exception.ServiceException;
import cn.cj.erp.common.redis.RedisCache;
import cn.cj.erp.common.redis.RedisKeyEnum;
import cn.cj.erp.common.security.security.asyncjob.AsyncFactory;
import cn.cj.erp.common.security.security.service.SecurityLoginService;
import cn.cj.erp.common.security.security.utils.SecurityUtils;
import cn.cj.erp.common.threadpool.AsyncManager;
import cn.cj.erp.common.vo.RouterVo;
import cn.cj.erp.common.vo.login.LoginUserResponseVo;
import cn.cj.erp.common.vo.login.LoginVo;
import cn.cj.erp.service.LoginService;
import cn.cj.erp.common.http.Result;
import cn.cj.erp.modules.common.controller.AbstractController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * 登录相关
 *
 * @author chenjian
 */
@Slf4j
@Validated
@RestController
public class LoginController extends AbstractController {
    @Resource
    private SecurityLoginService securityLoginService;
    @Resource
    private RedisCache redisCache;
    @Resource
    private LoginService loginService;

    /**
     * 登录
     */
    @PostMapping(value = "/login")
    public Result<String> login(@Valid @RequestBody LoginVo loginVo) {
        loginVo.decrypt();
        validateCaptcha(loginVo);
        String token = securityLoginService.login(loginVo.getUsername(), loginVo.getPassword());
        return Result.ok(token);
    }

    /**
     * 获取登录用户信息
     * @return 用户信息
     */
    @GetMapping("/getLoginUserInfo")
    public Result<LoginUserResponseVo> getLoginUserInfo() {
        return Result.ok(loginService.getLoginUserInfo(SecurityUtils.getLoginUser().getUser()));
    }

    /**
     * 获取路由信息
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    public Result<List<RouterVo>> getRouters() {
        return Result.ok(loginService.getRouters(SecurityUtils.getUserId()));
    }

    /**
     * 校验验证码
     *
     * @param loginVo 登录请求
     */
    private void validateCaptcha(LoginVo loginVo) {
        String redisKey = RedisKeyEnum.LOGIN_CAPTURE.getKey(loginVo.getUuid());
        String captchaInner = redisCache.get(redisKey);
        redisCache.delete(redisKey);
        if (!loginVo.getCode().equalsIgnoreCase(captchaInner)) {
            log.error("用户【{}】登录失败：{}", loginVo.getUsername(), "验证码不符");
            AsyncManager.getInstance().execute(AsyncFactory
                    .saveLoginLog(loginVo.getUsername(), StatusEnum.ABNORMAL, "验证码不符"));
            throw new ServiceException("验证码不符");
        }
    }
}
